import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/users/Users.vue'
import Role from '../components/role/Role.vue'
import Group from '../components/group/Group.vue'
import RightMs from '../components/role/RightMs.vue'
import Permis from '../components/group/Permis.vue'
import Brand from '../components/category_brand/Brand.vue'
import Category from '../components/category_brand/Category.vue'
import Goods from '../components/goods/Goods.vue'
import SpecGroup from '../components/spec/SpecGroup'
import Order from '../components/order/Order.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/home/welcome',
    children: [
      { path: 'welcome', component: Welcome },
      { path: 'users', component: Users },
      { path: 'role', component: Role },
      { path: 'group', component: Group },
      { path: 'right/ms', component: RightMs },
      { path: 'permis/ms', component: Permis },
      { path: 'brand', component: Brand },
      { path: 'goods', component: Goods },
      { path: 'category', component: Category },
      { path: 'spec_group', component: SpecGroup },
      { path: 'order', component: Order }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由守卫配置
// beforeEach：表示每一次切换路由地址时，都将进入此方法中
// to: 你想要去哪里，to.path：获得需要访问的组件对应的hash
// from: 你从哪里来
// next: 函数，操作方式一： next() 放行。  操作方式二： next('新地址')
router.beforeEach((to, from, next) => {
  // 只要是访问登录页面，一律放行
  if (to.path === '/login') {
    return next()
  }
  // 登录后，对所有页面进行放行
  const token = sessionStorage.getItem('RICERVCVCER-TOKEN')
  // 如果没有登录
  if (!token) {
    // 跳转到登录页面（修改hash为/login）
    return next('/login')
  }
  // 如果登录了
  next()
})

export default router
